package com.intelligentmeterreadingsys.waterlist.reviewdata.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.graphics.Color;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.util.BluetoothHelp;
import com.intelligentmeterreadingsys.util.CHexConver;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.ImageSwitcherActivity;
import com.intelligentmeterreadingsys.waterlist.reviewdata.db.ReviewDataDao;

import dbhelper.XmlNameHelper;

/**
 * RFID数据审核
 * 
 * @author king
 * 
 */
public class ReviewDataActivity extends Activity implements OnClickListener {
	public static final int ITEM0 = Menu.FIRST;// 系统值
	private final static int DIALOG = 1;

	public String xieyi = "15693";
	public Button button1;// 保存
	public Button button2;// 读卡
	public Button button3;// 上传
	public EditText edit1;// 复查刻度
	public EditText edit2;// 备注
	public TextView textview1;// 用户姓名
	public TextView textview8;// 用户编号
	public TextView textview2;// 水表编号
	public TextView textview3;// 水表地址
	public TextView textview4;// 用水性质
	public TextView textview5;// 水表中径
	public TextView textview6;// 上次抄表刻度
	public TextView textview7;// 用水量
	public String RFIDnumber;

	public ProgressDialog pd;// 读卡进度条
	public boolean isStop = true;
	public long time;
	public UserWaterVO water = null;
	public boolean isalarm = false;
	public boolean isupload = false;
	public boolean isSave = false;
	public String readtype = "NFC读卡";
	public String[] readdate;
	public BluetoothHelp bluehelp;

	private NfcAdapter mAdapter;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.review_water_query);

		init();
	}

	/**
	 * 初始化控件
	 */
	public void init() {
		readtype = "终端读卡";
		button1 = (Button) findViewById(R.id.review_query_paizhao);
		button2 = (Button) findViewById(R.id.review_query_save);
		button3 = (Button) findViewById(R.id.review_query_upload);
		textview1 = (TextView) findViewById(R.id.review_query_username);
		textview2 = (TextView) findViewById(R.id.review_query_waternumber);
		textview3 = (TextView) findViewById(R.id.review_query_wateradds);
		textview4 = (TextView) findViewById(R.id.review_query_waterproperties);
		textview5 = (TextView) findViewById(R.id.review_query_metercaliber);
		textview6 = (TextView) findViewById(R.id.review_query_opendegree);
		textview7 = (TextView) findViewById(R.id.review_query_usewater);
		textview8 = (TextView) findViewById(R.id.treview_query_usernumber);
		edit1 = (EditText) findViewById(R.id.review_query_thismonthwater);

		edit2 = (EditText) findViewById(R.id.review_query_desc);
		edit1.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (water != null && !TextUtils.isEmpty(s.toString())) {
					Double usewater = Double.parseDouble(s.toString())
							- water.getLastmonthwater();
					if (usewater < water.getLowalarmlimit()
							| usewater > water.getAlarmlimit()) {
						textview7.setText(usewater + "");
						textview7.setTextColor(Color.RED);
						isalarm = true;
					} else {
						textview7.setText(usewater + "");
						textview7.setTextColor(Color.BLACK);
						isalarm = false;
					}
				}

			}
		});
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		isStop = true;

		Toast.makeText(this, "正在读卡，请将终端靠近读卡器！", 1000).show();
		bluehelp = new BluetoothHelp(this);
		bluehelp.init();
		mAdapter = NfcAdapter.getDefaultAdapter(this);

		mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		try {
			ndef.addDataType("*/*");
			mFilters = new IntentFilter[] { ndef, };
			mTechLists = new String[][] {
					new String[] { NfcV.class.getName() },
					new String[] { MifareClassic.class.getName() } };

		} catch (MalformedMimeTypeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void onClick(View v) {

		if (button2.getId() == v.getId()) {
			if (readtype.equals("蓝牙读卡")) {
				bluehelp.start();
				new Thread() {

					@Override
					public void run() {

						while (isStop) {

							String id = RFIDnumber = "";
							if (readtype.equals("终端读卡")) {

							} else {

								id = RFIDnumber = bluehelp.getRfidId();
							}

							if (!TextUtils.isEmpty(id)) {
								isStop = false;
								Message msg = MyHandler.obtainMessage();
								msg.what = 1;
								msg.obj = id;
								MyHandler.sendMessage(msg);
							}
							try {
								Thread.sleep(200);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						super.run();

					}

				}.start();
			} else {
				pd = new ProgressDialog(this);
				pd.setMessage("扫描中......");
				pd.show();
				if (mAdapter == null) {
					Toast.makeText(this, "请打开NFC功能块", Toast.LENGTH_SHORT)
							.show();
					return;
				}
			}
		}
		;
		if (button3.getId() == v.getId()) {
			if (water == null) {
				Toast.makeText(this, "没有水表信息不能操作", Toast.LENGTH_SHORT).show();
				return;
			}
			if (!isSave) {
				Toast.makeText(ReviewDataActivity.this, "还没保存不能上传",
						Toast.LENGTH_LONG).show();

				return;
			}
			if (isupload) {
				Toast.makeText(ReviewDataActivity.this, "已经上传过了",
						Toast.LENGTH_LONG).show();

				return;
			}
			pd = new ProgressDialog(this);
			pd.setMessage("上传中....");
			pd.show();
			new Thread() {
				@Override
				public void run() {
					RequestUrl Req = new RequestUrl(ReviewDataActivity.this);
					String url = Req.getUrl(RequestUrl.COPYWATERLIST);
					SharedPreferenceUtil sh = new SharedPreferenceUtil(
							ReviewDataActivity.this);

					ReviewDataDao dao = new ReviewDataDao(
							ReviewDataActivity.this);
					WaterInfoVO waterinfo = dao.queryOneNoUpload(water
							.getWaterid());

					Map<String, String> map = new HashMap<String, String>();
					Map<String, String> map1 = new HashMap<String, String>();
					map1.put("waternumber", waterinfo.getWaternumber());
					map1.put("thismonthwater" + "",
							waterinfo.getThismonthwater() + "");
					String usewater = (waterinfo.getThismonthwater() - waterinfo
							.getLastmonthwater()) + "";
					map1.put("usewater", usewater);
					map1.put("thisdate", waterinfo.getThisdate());
					map1.put("imsi", sh.getValue(XmlNameHelper.IMSI));
					map1.put("desc", waterinfo.getDesc());
					map1.put("sid", waterinfo.getSid());
					map1.put("isnorfid", waterinfo.getIsNorfid());
					Map<File, String> mapfile = new HashMap<File, String>();
					List<String> list = waterinfo.getImagepath();
					for (int i = 0; i < list.size(); i++) {
						File file = new File(list.get(i));
						if (file.exists()) {
							map.put(file.getName(), "imagename");
							mapfile.put(file, "imagepath");
						}
					}
					dao.close();
					try {

						String respon = UploadHttpClient.uploadSubmit(url, map,
								mapfile, map1);
						System.out.println(respon);
						if (respon.equals("error")) {
							Message msg = UpoladHandle.obtainMessage();
							msg.what = 1;
							UpoladHandle.sendMessage(msg);
						} else {
							pd.dismiss();
							JSONObject json = new JSONObject(respon);
							String message = json.getString("message");
							if (message.equals("no")) {
								Message msg = UpoladHandle.obtainMessage();
								msg.what = 2;
								UpoladHandle.sendMessage(msg);
								return;
							} else {
								Message msg = UpoladHandle.obtainMessage();
								msg.what = 3;
								UpoladHandle.sendMessage(msg);
								return;
							}

						}

					} catch (Exception e) {
						Message msg = UpoladHandle.obtainMessage();
						msg.what = 2;
						UpoladHandle.sendMessage(msg);
					}

				}

			}.start();

		}

		if (button1.getId() == v.getId()) {
			if (water == null) {
				Toast.makeText(this, "没有水表信息不能操作", Toast.LENGTH_SHORT).show();
				return;
			}

			if (isupload) {
				Toast.makeText(ReviewDataActivity.this, "已经上传了不能保存",
						Toast.LENGTH_LONG).show();
				return;
			}
			boolean b = save();
			if (b) {
				Toast.makeText(ReviewDataActivity.this, "保存成功",
						Toast.LENGTH_LONG).show();
				isSave = true;
				return;
			}
		}

	}

	/**
	 * 展现数据
	 */

	public void viewDate() {
		textview1.setText("");
		textview2.setText("");
		textview3.setText("");
		textview4.setText("");
		textview5.setText("");
		textview6.setText("");
		textview7.setText("");
		edit1.setText("");
		edit2.setText("");
		if (water != null) {
			textview1.setText(water.getName());
			textview2.setText(water.getWaternumber());
			textview3.setText(water.getWateradds());
			textview4.setText(water.getWaterproperties());
			textview5.setText(water.getMetercaliber());
			textview6.setText(water.getLastmonthwater() + "");
			if (water.getThismonthwater() > 0) {
				edit1.setText(water.getThismonthwater() + "");
				edit2.setText(water.getDesc());
				textview7.setText(water.getThismonthwater()
						- water.getLastmonthwater() + "");
			}
		}

	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public boolean save() {
		boolean b = false;
		if (water.getIsupload().equals("1")) {
			Toast.makeText(ReviewDataActivity.this, "已经上传过了不能再抄了", 1000).show();
			return false;
		}
		ReviewDataDao dao = new ReviewDataDao(this);
		b = dao.isPhotograph(water.getWaterid());
		if (textview7.getCurrentTextColor() == Color.RED && b == false) {
			Toast.makeText(ReviewDataActivity.this, "报警水表需拍照", 1000).show();
			dao.close();
			return false;
		}

		if (RFIDnumber != null && water != null) {
			Double thismothwater = Double.parseDouble(edit1.getEditableText()
					.toString());
			String desc = textview7.getText().toString();

			b = dao.saveWater(water.getWaternumber(), thismothwater, desc, "0");
			dao.close();
		}

		return b;

	}

	/**
	 * 关闭读卡
	 */
	public void close() {

		bluehelp.stop();
	}

	@Override
	protected void onDestroy() {
		isStop = false;
		close();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, ITEM0, 0, "短息通知");

		menu.add(0, ITEM0 + 1, 0, "RFID协议");
		menu.add(0, ITEM0 + 2, 0, "读卡方式");
		menu.add(0, ITEM0 + 3, 0, "拍照");
		menu.findItem(ITEM0 + 1);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == ITEM0) {
			if (water == null) {
				Toast.makeText(ReviewDataActivity.this, "没查到用户无法发送",
						Toast.LENGTH_LONG).show();
				return false;
			}
			Uri smsToUri = Uri.parse("smsto:");
			String userwater = textview7.getText().toString();
			Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);
			sendIntent.putExtra("address", water.getPhone()); // 电话号码，这行去掉的话，默认就没有电话
			sendIntent.putExtra("sms_body", "尊敬的" + water.getName()
					+ "用户:你本月用水量为:" + userwater);
			sendIntent.setType("vnd.android-dir/mms-sms");
			startActivity(sendIntent);
		} else if (item.getItemId() == (ITEM0 + 1)) {
			showDialog(DIALOG);
		} else if (item.getItemId() == (ITEM0 + 2)) {
			showDialog(DIALOG + 2);
		} else if (item.getItemId() == ITEM0 + 3) {

			Intent intent = new Intent(this, ImageSwitcherActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("otherid", water.getWaterid());
			bundle.putString("status", "3");
			bundle.putString("classname", "ReviewDataActivity");
			startActivity(intent);

		}
		return false;
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		Dialog dialog = null;
		switch (id) {
		case DIALOG:
			Builder builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("单选按钮对话框");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(R.array.hobby, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							xieyi = getResources()
									.getStringArray(R.array.hobby)[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (xieyi.equals("15693")) {

							} else if (xieyi.equals("14443")) {

							}
						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		case DIALOG + 2:
			if (readtype.equals("终端读卡")) {
				readdate = new String[] { "终端读卡", "蓝牙读卡" };
			} else {
				readdate = new String[] { "蓝牙读卡", "终端读卡" };
			}

			builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);
			// 设置对话框的标题
			builder.setTitle("读卡方式选择");
			// 0: 默认第一个单选按钮被选中

			builder.setSingleChoiceItems(readdate, 0,
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							readtype = readdate[which];

						}
					});

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							time = System.currentTimeMillis();
							if (readtype.equals("蓝牙读卡")) {
								bluehelp.start();
							}
							isStop = true;

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();
			break;
		}
		return dialog;
	}

	/**
	 * 读卡消息接收
	 */
	public Handler MyHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			long times = System.currentTimeMillis();
			if (times - time > 12000) {
				Toast.makeText(ReviewDataActivity.this, "读卡超时",
						Toast.LENGTH_SHORT).show();
				isStop = false;
				if (readtype.equals("NFC读卡")) {
					pd.dismiss();
				} else {
					bluehelp.close();
				}
				return;
			}
			if (msg.what == 1) {
				isStop = false;
				if (readtype.equals("NFC读卡")) {
					pd.dismiss();
				} else {
					bluehelp.close();
				}
				ReviewDataDao dao = new ReviewDataDao(ReviewDataActivity.this);

				water = dao.queryOneReview(RFIDnumber, null);
				dao.close();

				if (water != null) {
					Toast.makeText(ReviewDataActivity.this,
							"读卡成功" + RFIDnumber, Toast.LENGTH_LONG).show();
					if (water.getIsupload().equals("1")) {
						isupload = true;
					}
				} else {
					Toast.makeText(ReviewDataActivity.this, "此RFID卡还未绑定水表",
							Toast.LENGTH_LONG).show();
					return;
				}

				TipHelper.Vibrate(ReviewDataActivity.this, 1000);

			} else {
				Toast.makeText(ReviewDataActivity.this, "读卡超时",
						Toast.LENGTH_LONG).show();

			}
		}

	};

	/**
	 * 上传
	 * 
	 * @return
	 */
	public Handler UpoladHandle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				pd.dismiss();
				Toast.makeText(ReviewDataActivity.this, "请检查网络", 1000).show();
			} else if (msg.what == 2) {
				pd.dismiss();
				Toast.makeText(ReviewDataActivity.this, "上传失败", 1000).show();
			} else if (msg.what == 3) {
				pd.dismiss();
				Toast.makeText(ReviewDataActivity.this, "上传成功",
						Toast.LENGTH_LONG).show();
				isupload = true;
			}
		}

	};

	@Override
	protected void onPause() {

		mAdapter.disableForegroundDispatch(this);

		super.onPause();
	}

	@Override
	protected void onResume() {
		mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
				mTechLists);

		super.onResume();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// if (isStop) {
		// return;
		// }

		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
			Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			for (String tech : tagFromIntent.getTechList()) {
				System.out.println(tech);
			}
			time = System.currentTimeMillis();
			MifareClassic mf = MifareClassic.get(tagFromIntent);

			if (mf != null) {

				RFIDnumber = CHexConver.bytesToHexStrings(mf.getTag().getId());
				Message msg = MyHandler.obtainMessage();
				msg.what = 1;
				msg.obj = RFIDnumber;
				MyHandler.sendMessage(msg);
			}
			NfcV nf = NfcV.get(tagFromIntent);
			if (nf != null) {
				RFIDnumber = CHexConver.bytesToHexStrings(nf.getTag().getId());
				Message msg = MyHandler.obtainMessage();
				msg.what = 1;
				msg.obj = RFIDnumber;
				MyHandler.sendMessage(msg);
			}

		}

		super.onNewIntent(intent);
	}
}
